#!/bin/sh
# This file shall replace file "/lib/systemd/systemd-shutdown":
# ( set -xv; f=/lib/systemd/systemd-shutdown; [ -e $f.old ] || sudo cp -a $f $f.old; cat systemd-shutdown.sh | sudo tee $f >/dev/null; echo rt=$? )
#
# enable console, systemd run systemd-shutdown without console
exec </dev/console >/dev/console 2>&1
echo "$0" "$@"
#set +e
#set -xv; pwd; env
#export PATH=/sbin:/bin:$PATH
#
pgrep -a "\<mount\." || {
	mv /run/initramfs/shutdown.old /run/initramfs/shutdown
	echo "No fusermount found, exec /lib/systemd/systemd-shutdown.old" "$@"
	exec /lib/systemd/systemd-shutdown.old "$@"
}
#exec bash -i
#
v=false
[ z"$-" != z"${-#*x}" ] && v=true
#
$v && {
	/bin/sleep 2
	#/bin/bash -i <dev/console >dev/console 2>&1
	echo "Before pivot_root."
	#/bin/bash -i
}
#
mount -o remount,exec /run
mount -v -o bind /run/initramfs /run/initramfs
mount -v --make-private /run/initramfs
mount -v --make-rprivate /
#
$v && ls -l /proc/self/fd/*
{ cd /run/initramfs &&
mkdir -p oldroot &&
pivot_root . oldroot; } || { echo "pivot_root failed."; bash -i; }
#
# now root changed after pivot_root
# mount proc dev and sys
cd /
mkdir -p proc sys dev/pts
mount -v -t proc proc /proc
$v && { cat /proc/mounts; ls -l /proc/self/fd/*; }
#mount -v -t devtmpfs dev /dev
#mount -v -t devpts devpts /dev/pts
mount -v -o move /oldroot/dev /dev || { echo "Move mount dev failed."; bash -i; }
mount -v -t sysfs sysfs /sys
# switch to new /dev/console, release old console
$v && ls -l /proc/self/fd/*
sync
exec 2>&- 1>&- 0<&-; exec </dev/console >/dev/console 2>&1
$v && ls -l /proc/self/fd/*
#
$v && {
	#/bin/sleep 2
	echo "Before exec /shutdown.old"
	/bin/sh -i
}
#
# "exec" run program without original console, otherwise "lsof /oldroot/" will list the forked process and "umount /oldroot/dev/" will fail on busy. Or, move mount dev "mount -v -o move /oldroot/dev /dev".
exec /bin/sh -xvc '/lib/systemd/system-shutdown/livecd.mounts.finalrd "$@"; [ $# -gt 0 ] && [ "1" = "$$" ] && exec /shutdown.old "$@"; echo "Unexpected to here."; /bin/sleep 3; exec /bin/sh -i' x "$@"
#
# should not run to here
#echo "End of systemd-shutdown: $*"
#exec /bin/sh -i

